package com.zhuanzhuan.hero.user.helper;

import com.bj58.youpin.common.rpc.result.Result;
import com.bj58.youpin.common.utils.json.JsonUtils;
import com.google.common.collect.Maps;
import com.zhuanzhuan.hero.biz.common.util.WxWarnTemplateUtil;
import com.zhuanzhuan.hero.user.consts.Consts;
import com.zhuanzhuan.hero.user.enums.ExceptionMsgEnum;
import com.zhuanzhuan.hero.user.exception.BusinessException;
import com.zhuanzhuan.hero.user.util.AsyncUtil;
import com.zhuanzhuan.hero.user.util.RetryUtil;
import com.zhuanzhuan.hero.user.util.RpcUtil;
import com.zhuanzhuan.hero_message.facade.IHeroMessageFacade;
import com.zhuanzhuan.hero_message.module.HeroBatchRecentChatNumRequestDTO;
import com.zhuanzhuan.hero_message.module.HeroUpdateUserInfoRequestDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName ImHelper
 * @Description  与IM的交互
 * @Author hanjunjun
 * @Date 2024/7/3 10:51
 */
@Component
@Slf4j
public class ImHelper {

    @Resource
    private IHeroMessageFacade heroMessageFacade;

    /**
     * 注册IM用户
     *
     * @param uid
     * @param nickname
     * @param profilePhoto
     * @return boolean
     * @author  hanjunjun
     * @date 2024/7/3
     **/
    public boolean createImUser(Long uid, String nickname, String profilePhoto) {
        HeroUpdateUserInfoRequestDTO dto = new HeroUpdateUserInfoRequestDTO();
        dto.setUid(String.valueOf(uid));
        dto.setNickName(nickname);
        dto.setAvatarUrl(profilePhoto);

        AsyncUtil.run(() -> {
            RetryUtil.retryRunableNoInterval(() -> {
                log.info("call createImUser param={}", JsonUtils.toJsonWithoutNull(dto));
                Result<String> result = heroMessageFacade.createImUser(dto);
                log.info("call createImUser result={}", JsonUtils.toJsonWithoutNull(result));
                if (!result.isSuccess()) {
                    WxWarnTemplateUtil.warnOutInvokedService(Consts.SERVICE_NAME, Consts.MESSAGE_SERVICE_NAME, "createImUser调用失败");
                    throw new BusinessException(ExceptionMsgEnum.BUSINESS_ERROR);
                }
            });
        });

        return true;
    }

    /**
     * 更新用户
     *
     * @param uid
     * @param nickname
     * @param profilePhoto
     * @return boolean
     * @author  hanjunjun
     * @date 2024/7/3
     **/
    public boolean updateImUserAsync(Long uid, String nickname, String profilePhoto) {
        if (StringUtils.isBlank(nickname) && StringUtils.isBlank(profilePhoto)) {
            log.info("昵称头像都为空，不调用im更新");
            return true;
        }

        HeroUpdateUserInfoRequestDTO dto = new HeroUpdateUserInfoRequestDTO();
        dto.setUid(String.valueOf(uid));
        dto.setNickName(nickname);
        dto.setAvatarUrl(profilePhoto);

        AsyncUtil.run(() -> {
            RetryUtil.retryRunableNoInterval(() -> {
                log.info("call updateUserInfo param={}", JsonUtils.toJsonWithoutNull(dto));
                Result<String> result = heroMessageFacade.updateUserInfo(dto);
                log.info("call updateUserInfo result={}", JsonUtils.toJsonWithoutNull(result));
                if (!result.isSuccess()) {
                    WxWarnTemplateUtil.warnOutInvokedService(Consts.SERVICE_NAME, Consts.MESSAGE_SERVICE_NAME, "updateUserInfo调用失败");
                    throw new BusinessException(ExceptionMsgEnum.BUSINESS_ERROR);
                }
            });
        });

        return true;
    }

    /**
     * 删除用户
     *
     * @param uid
     * @return boolean
     * @author  hanjunjun
     * @date 2024/7/3
     **/
    public boolean deleteImUser(Long uid) {
        AsyncUtil.run(() -> {
            RetryUtil.retryRunableNoInterval(() -> {
                log.info("call deleteImUser param={}", uid);
                Result<String> result = heroMessageFacade.deleteUser(uid);
                log.info("call deleteImUser result={}", JsonUtils.toJsonWithoutNull(result));
                if (!result.isSuccess()) {
                    WxWarnTemplateUtil.warnOutInvokedService(Consts.SERVICE_NAME, Consts.MESSAGE_SERVICE_NAME, "deleteUser调用失败");
                    throw new BusinessException(ExceptionMsgEnum.BUSINESS_ERROR);
                }
            });
        });

        return true;
    }

    public Map<Long, Long> batchGetRecentChatNum(List<Long> uidList, int days) {
        if(CollectionUtils.isEmpty(uidList)){
            return Maps.newHashMap();
        }
        log.info("call recent chat num uidList={} days={}", uidList, days);
        HeroBatchRecentChatNumRequestDTO request = new HeroBatchRecentChatNumRequestDTO();
        request.setUidSet(new HashSet<>(uidList.stream()
                .filter(Objects::nonNull)
                .map(String::valueOf)
                .collect(Collectors.toList())));
        Date end = new Date();
        Date start = DateUtils.addDays(end, -days);
        request.setStartTime(start);
        request.setEndTime(end);
        Result<Map<String, Long>> result = heroMessageFacade.getBatchRecentChatNum(request);
        Map<String, Long> map = RpcUtil.extractResult(result, request);
        if(MapUtils.isEmpty(map)){
            return Maps.newHashMap();
        }
        return map.entrySet().stream().collect(Collectors.toMap(e -> Long.valueOf(e.getKey()), Map.Entry::getValue));
    }


}
